/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse;

import java.util.*;
import java.io.File;
import java.sql.*;

/**************
 * This class monitors files based on a sensorID/appID pair from the metadata.
 * It tracks how much of a file has been processed.
 * 
 * @author bduphoff
 * 
 */

public class DataFileMonitor extends Thread {

	/********************
	 * A collection of DataFileProcessor objects that tracks files being
	 * processed by the system for this sensor/app pair.
	 */
	private Vector<DataFileProcessor> fileProcessors = new Vector<DataFileProcessor>();

	/******************
	 * The maximum number of file processors that can be active at any given
	 * time.
	 */
	private int maxFileProcessors = 2;

	/****************
	 * The sensor ID part of the sensor/app identifier for this instance.
	 */
	private int sensorID = -1;

	/****************
	 * The application ID part of the sensor/app identifier for this instance.
	 */
	private int appID = -1;

	/********************
	 * A database connection used by this instance to access the system
	 * metadata.
	 */
	private MetaDatabase mdb = null;
	
	/***************
	 * The number of milliseconds to wait if maxFileProcessors has been reached.
	 */
	private int waitInterval = 10000;

	public int getWaitInterval() {
		return waitInterval;
	}

	public void setWaitInterval(int waitInterval) {
		this.waitInterval = waitInterval;
	}

	/***************
	 * Constructor that allows the number of file processors to be set along
	 * with the required sensor/app pair.
	 * 
	 * @param sensorID
	 * @param appID
	 * @param maxFileProcessors
	 */
	public DataFileMonitor(int sensorID, int appID, int maxFileProcessors) {
		this.sensorID = sensorID;
		this.appID = appID;
		this.maxFileProcessors = maxFileProcessors;
	}

	/***************
	 * Creates a DataFileMonitor instance to process files for a given
	 * sensor/app pair.
	 * 
	 * @param sensorID
	 * @param appID
	 */
	public DataFileMonitor(int sensorID, int appID) {
		this.sensorID = sensorID;
		this.appID = appID;
	}

	/**********
	 * Allows supporting classes to access the appID attribute.
	 * 
	 * @return The app ID attribute
	 */
	public int getAppID() {
		return appID;
	}

	/*******
	 * Updates the system metadata to indicate that a file has been processed.
	 * Called by DataFileProcessor instance spawned by this instance of
	 * DataFileMonitor.
	 * 
	 * @param fileID
	 *            The file identifier to set as processed
	 * @throws Exception
	 */
	public void setFileProcessed(int fileID) throws Exception {
		Statement s = mdb.createStatement();
		String sql = "update data_files_by_app set Status=1 where App_ID="
				+ appID + " and File_ID=" + fileID;
		s.execute(sql);
		s.close();
	}

	/**********
	 * Allows supporting classes to access the sensor ID attribute.
	 * 
	 * @return The sensor ID attribute
	 */
	public int getSensorID() {
		return sensorID;
	}

	public void run() {
		try {
			if (sensorID == -1 || appID == -1) {
				throw (new Exception(
						"Sensor/app ID pair was invalid. Must be non-negative and consistent with values in the system metadata."));
			}
			if (maxFileProcessors == -1) {
				throw (new Exception(
						"Value for maxFileProcessors must be non-negative."));
			}

			// Create a connection to the system metadata
			mdb = MetaDatabase.create();

			// Loop forever until an Exception is thrown or the system exits.
			// Does not handle failure of the loop as well as it could.
			while (true) {

				// Check to see if any threads are done
				int idx = 0;
				while (idx < fileProcessors.size()) {
					DataFileProcessor fileProcessor = (DataFileProcessor) fileProcessors
							.elementAt(idx);
					if (!fileProcessor.isAlive()) {
						fileProcessors.remove(idx);
					} else {
						idx++;
					}
				}

				// If there are less than maxFileProcessors threads, start a
				// news one, otherwise wait
				if (fileProcessors.size() < maxFileProcessors) {

					// Create the SQL clause to select a fileID not being
					// processed already
					String fileIdSQL = " and ";
					for (int i = 0; i < fileProcessors.size(); i++) {
						DataFileProcessor fileProcessor = (DataFileProcessor) fileProcessors
								.elementAt(i);
						fileIdSQL += " a.File_ID != " + fileProcessor.getFileID()
								+ " and ";
					}

					// Broken. need to a way to see if the file is already being
					// processed by a thread
					String sql = "select c.App_Class as App_Class, a.Path as Path, c.Name as Name, b.Record_Offset as Record_Offset, c.App_ID as App_ID, a.File_ID as File_ID, b.Status as Status from data_files a, data_files_by_app b, app_list c where a.Node_ID="
							+ NetFSE.NODE_ID
							+ " and a.File_ID=b.File_ID and b.App_ID=c.App_ID "
							+ fileIdSQL
							+ " a.Status=1 and b.Status=0 and a.Sensor_ID="
							+ sensorID
							+ " and b.App_ID="
							+ appID
							+ " limit "
							+ (maxFileProcessors - fileProcessors.size());

					// System.out.println(sql);
					Statement s = mdb.createStatement();
					ResultSet rs = s.executeQuery(sql);
					int count = 0;
					while (rs.next()) {
						try {
							/************
							 * All we have done so far is find files that need
							 * to be processed. The next block of code
							 * instantiates a DataFileProcessor, sets its fields
							 * and then starts it, which ultimately processes
							 * the file content, accoring to the class name
							 * stored in the app_class field.
							 */
							DataFileProcessor fileProcessor = (DataFileProcessor) Class
									.forName(rs.getString("app_class"))
									.newInstance();
							fileProcessor.setFilePath(rs.getString("Path"));
							File f = new File(fileProcessor.getFilePath());
							if (!f.exists()) {
								throw (new Exception(
										"File specified does not exist: '"
												+ f.getAbsolutePath() + "'s"));
							}
							fileProcessor.setAppName(rs.getString("Name"));
							fileProcessor.setSensorID(sensorID);
							fileProcessor.setOffset(rs.getInt("Record_Offset"));
							fileProcessor.setStatus(rs.getInt("Status"));
							fileProcessor.setAppID(rs.getInt("App_ID"));
							fileProcessor.setFileID(rs.getInt("File_ID"));
							fileProcessor.setDataFileMonitor(this);
							fileProcessors.addElement(fileProcessor);
							fileProcessor.start();
							count++;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					if (count == 0) {
						// No files to process so sleep for 10 seconds
						Thread.sleep(waitInterval);
					}
					rs.close();
					s.close();
				} else {
					// Too many threads in progress, sleep for 10 seconds
					Thread.sleep(waitInterval);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}